package com.menghanjun.mhjresourcesharing.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:jwt.properties")
public class JwtUtils {
    // 设置固定的密钥
    @Value("${jwt.secret}")
    private String secretKey;

    public  String generateToken(String subject) {
        return Jwts.builder()
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public String getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    public static void main(String[] args) {
        // 生成一个256位的密钥
        byte[] keyBytes = Keys.secretKeyFor(SignatureAlgorithm.HS256).getEncoded();

        // 将密钥字节数组转换为十六进制字符串
        StringBuilder hexKey = new StringBuilder();
        for (byte b : keyBytes) {
            hexKey.append(String.format("%02x", b));
        }

        /*System.out.println("Generated Key: " + hexKey.toString());
        System.out.println(Keys.secretKeyFor(SignatureAlgorithm.HS256));
        String s = JwtUtils.generateToken("12345678");
        System.out.println(s);
        String userIdFromToken = JwtUtils.getUserIdFromToken(s);
        System.out.println(userIdFromToken);*/
    }
}
